package com.hzeport.bgs22emduty.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hzeport.bgs22emduty.config.SystemConfig;
import com.hzeport.bgs22emduty.dto.DutyScheduleInfoTimeDTO;
import com.hzeport.bgs22emduty.dto.DutyScheduleInfoTimeDetailDTO;
import com.hzeport.bgs22emduty.entity.*;
import com.hzeport.bgs22emduty.outbound.*;
import com.hzeport.bgs22emduty.outbound.db.DutyScheduleInfoRepositoryImpl;
import com.hzeport.bgs22emduty.service.BaseDeptInfoService;
import com.hzeport.bgs22emduty.service.DutyScheduleInfoService;
import com.hzeport.bgs22emduty.service.ParamHolidaysService;
import com.masa.common.core.base.BaseResult;
import com.masa.common.data.base.BaseServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.ChronoField;
import java.util.List;
import java.util.stream.Collectors;

/**
 * ${comments}
 *
 * @author code generator
 * @date 2022-12-02 11:21:59
 */
@Service
@Slf4j
public class DutyScheduleInfoServiceImpl extends BaseServiceImpl<DutyScheduleInfoRepositoryImpl, DutyScheduleInfo> implements DutyScheduleInfoService {

    @Resource
    private DutyScheduleInfoRepository dutyScheduleInfoRepository;
    @Resource
    private ParamDutyRepository paramDutyRepository;
    @Resource
    private BasePersonInfoRepository basePersonInfoRepository;
    @Resource
    private BaseDeptInfoRepository baseDeptInfoRepository;
    @Resource
    private ParamLeaderRepository paramLeaderRepository;

    @Override
    public BaseResult<DutyScheduleInfoTimeDTO> nowUser(String customnName) {
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime tomorrow = LocalDateTime.now().toLocalDate().plusDays(1l).atStartOfDay();
        DutyScheduleInfoTimeDTO todayDTO = getTimeDTOForNow(customnName, now);
        DutyScheduleInfoTimeDTO tomorrowDTO = getTimeDTOForNow(customnName, tomorrow);
        String todayString = getStringByTimeDTO(todayDTO);
        String tomorrowString = getStringByTimeDTO(tomorrowDTO);
        todayDTO.setTomorrowPerson(tomorrowString);
        todayDTO.setTodayPerson(todayString);
        return BaseResult.ok(todayDTO);
    }

    private String getStringByTimeDTO(DutyScheduleInfoTimeDTO todayDTO) {
        String todayString = "";
        if (todayDTO == null) {
            return "";
        }
        if (todayDTO.getKJInfo() != null) {
            if (todayDTO.getKJInfo().getSType()==null){
                todayString += todayDTO.getKJInfo().getDUsername();
                return todayString;
            }
            switch (todayDTO.getKJInfo().getSType()) {
                case "1":
                    todayString += todayDTO.getKJInfo().getDUsername();
                    return todayString;
                case "2":
                case "3":
                    todayString += todayDTO.getKJInfo().getDUsername();
                    break;
                default:
                    return "";
            }
        }
        if (todayDTO.getCJInfo() != null) {
            switch (todayDTO.getCJInfo().getSType()) {
                case "1":
                    return "";
                case "2":
                case "3":
                    if (StringUtils.isEmpty(todayString)) {
                        todayString += todayDTO.getCJInfo().getDUsername();
                    } else {
                        todayString = todayString + "、" + todayDTO.getCJInfo().getDUsername();
                    }
                    break;
                default:
                    return "";
            }
        }
        return todayString;
    }

    private DutyScheduleInfoTimeDTO getTimeDTOForNow(String customnName, LocalDateTime time) {
        BaseDeptInfo custom = baseDeptInfoRepository.getOne(new LambdaQueryWrapper<BaseDeptInfo>()
                .eq(BaseDeptInfo::getDeptName, customnName), false);
        if (custom==null){
            return  new DutyScheduleInfoTimeDTO();
        }
        LocalDateTime now = time;
        LocalDate today = time.toLocalDate();
        LocalDate yesterday = time.toLocalDate().minusDays(1l);
        List<DutyScheduleInfo> dutyScheduleInfos = dutyScheduleInfoRepository.list(
                new LambdaQueryWrapper<DutyScheduleInfo>()
                        .eq(DutyScheduleInfo::getCustomName, customnName)
                        .eq(DutyScheduleInfo::getDDay, today));
        if ("海关总署".equals(customnName)) {
//            if (!CollectionUtils.isEmpty(dutyScheduleInfos)){
            DutyScheduleInfoTimeDTO dutyScheduleInfoTimeDTO = new DutyScheduleInfoTimeDTO();
//            DutyScheduleInfoTimeDetailDTO dutyScheduleInfoTimeDetailDTO =
            DutyScheduleInfo dutyScheduleInfo= dutyScheduleInfoRepository.getOne(new LambdaQueryWrapper<DutyScheduleInfo>()
                    .eq(DutyScheduleInfo::getCustomName,"海关总署")
                    .eq(DutyScheduleInfo::getDDay,time.toLocalDate())
                    .eq(DutyScheduleInfo::getDutyType,"3"),false);
//                dutyScheduleInfoTimeDetailDTO.set
            DutyScheduleInfoTimeDetailDTO dutyScheduleInfoTimeDetailDTO=new DutyScheduleInfoTimeDetailDTO();
            if (dutyScheduleInfo!=null) {
                BeanUtils.copyProperties(dutyScheduleInfo, dutyScheduleInfoTimeDetailDTO);
            }else {
                dutyScheduleInfoTimeDetailDTO.setDUserno("");
                dutyScheduleInfoTimeDetailDTO.setDUsername("");
            }
            dutyScheduleInfoTimeDTO.setKJInfo(dutyScheduleInfoTimeDetailDTO);
            return dutyScheduleInfoTimeDTO;
//            }
        }
        DutyScheduleInfoTimeDTO result = new DutyScheduleInfoTimeDTO();
        if (CollectionUtils.isEmpty(dutyScheduleInfos)) {
            ParamLeader GLeader = paramLeaderRepository.getOne(new LambdaQueryWrapper<ParamLeader>()
                    .eq(ParamLeader::getDeptId, custom.getId())
                    .eq(ParamLeader::getLeaderName, "1"));
            ParamLeader CLeader = paramLeaderRepository.getOne(new LambdaQueryWrapper<ParamLeader>()
                    .eq(ParamLeader::getDeptId, custom.getId())
                    .eq(ParamLeader::getLeaderName, "2"));
            if (GLeader != null) {
                DutyScheduleInfoTimeDetailDTO managerInfo = new DutyScheduleInfoTimeDetailDTO();
                BaseDeptInfo baseDeptInfo = baseDeptInfoRepository.getById(GLeader.getDeptId());
                List<BasePersonInfo> basePersonInfos = basePersonInfoRepository.list(new LambdaQueryWrapper<BasePersonInfo>()
                        .eq(BasePersonInfo::getUserno, GLeader.getLeaderCode()));
                if (baseDeptInfo != null && !CollectionUtils.isEmpty(basePersonInfos)) {
                    BasePersonInfo basePersonInfo = basePersonInfos.get(0);
                    managerInfo.setDDeptname(baseDeptInfo.getDeptName());
                    managerInfo.setDPhone(basePersonInfo.getPhone());
                    managerInfo.setPhoneShort(basePersonInfo.getPhoneShort());
                    managerInfo.setDUsername(basePersonInfo.getUsername());
                    managerInfo.setDType("2");
                    managerInfo.setSType("1");
                    managerInfo.setDUserno(basePersonInfo.getUserno());
                    managerInfo.setDUserjob("关领导");
                    managerInfo.setDutypost(getDupostByH4a(basePersonInfo.getRealRackCode()));
                    managerInfo.setRankCode(basePersonInfo.getRankCode());
                    managerInfo.setFacePath(basePersonInfo.getFacePath());
                }
                result.setManagerInfo(managerInfo);
            }
            if (CLeader != null) {
                DutyScheduleInfoTimeDetailDTO CJInfo = new DutyScheduleInfoTimeDetailDTO();
                BaseDeptInfo baseDeptInfo = baseDeptInfoRepository.getById(CLeader.getDeptId());
                List<BasePersonInfo> basePersonInfos = basePersonInfoRepository.list(new LambdaQueryWrapper<BasePersonInfo>()
                        .eq(BasePersonInfo::getUserno, CLeader.getLeaderCode()));
                if (baseDeptInfo != null && !CollectionUtils.isEmpty(basePersonInfos)) {
                    BasePersonInfo basePersonInfo = basePersonInfos.get(0);
                    CJInfo.setDDeptname(baseDeptInfo.getDeptName());
                    CJInfo.setDPhone(basePersonInfo.getPhone());
                    CJInfo.setPhoneShort(basePersonInfo.getPhoneShort());
                    CJInfo.setDUsername(basePersonInfo.getUsername());
                    CJInfo.setDType("2");
                    //--------
                    CJInfo.setSType("2");
                    CJInfo.setDUserno(basePersonInfo.getUserno());
                    CJInfo.setDUserjob("处领导");
                    CJInfo.setDutypost(getDupostByH4a(basePersonInfo.getRealRackCode()));
                    CJInfo.setRankCode(basePersonInfo.getRankCode());
                    CJInfo.setFacePath(basePersonInfo.getFacePath());
                }
                result.setCJInfo(CJInfo);
            }
            return result;
        } else {
            DutyScheduleInfo dutyScheduleInfo = getSignInTaragetScheduleInfo(dutyScheduleInfos, now);
            DutyScheduleInfo current = new DutyScheduleInfo();
            switch (dutyScheduleInfo.getSType()) {
                case "1":
                    DayOfWeek day = DayOfWeek.of(today.get(ChronoField.DAY_OF_WEEK));
                    switch (day) {
                        case SATURDAY:
                        case SUNDAY:
                            List<DutyScheduleInfo> temp = dutyScheduleInfos.stream()
                                    .filter(i -> i.getDStartDateTime().compareTo(now)<0
                                            &&i.getDEndDateTime().compareTo(now)>0).collect(Collectors.toList());
                            if (!CollectionUtils.isEmpty(temp)) {
                                current = temp.get(0);
                            }
                            if (current.getId()==null){
                                current=dutyScheduleInfos.get(0);
                            }
                            break;
                        default:
                            temp = dutyScheduleInfos.stream()
                                    .filter(i -> i.getDutyTimesString().contains("夜间")).collect(Collectors.toList());
                            if (!CollectionUtils.isEmpty(temp)) {
                                current = temp.get(0);
                            }
                            if (current.getId()==null){
                                current=dutyScheduleInfos.get(0);
                            }
                    }
                    DutyScheduleInfoTimeDetailDTO currentTimeDetailDTO = new DutyScheduleInfoTimeDetailDTO();
                    BeanUtils.copyProperties(current, currentTimeDetailDTO);
                    currentTimeDetailDTO.setFacePath(getPathPath(current));
                    result.setKJInfo(currentTimeDetailDTO);
                    ParamLeader GLeader = paramLeaderRepository.getOne(new LambdaQueryWrapper<ParamLeader>()
                            .eq(ParamLeader::getDeptId, custom.getId())
                            .eq(ParamLeader::getLeaderName, "1"));
                    ParamLeader CLeader = paramLeaderRepository.getOne(new LambdaQueryWrapper<ParamLeader>()
                            .eq(ParamLeader::getDeptId, custom.getId())
                            .eq(ParamLeader::getLeaderName, "2"));
                    if (GLeader != null) {
                        DutyScheduleInfoTimeDetailDTO managerInfo = new DutyScheduleInfoTimeDetailDTO();
                        BaseDeptInfo baseDeptInfo = baseDeptInfoRepository.getById(GLeader.getDeptId());
                        List<BasePersonInfo> basePersonInfos = basePersonInfoRepository.list(new LambdaQueryWrapper<BasePersonInfo>()
                                .eq(BasePersonInfo::getUserno, GLeader.getLeaderCode()));
                        if (baseDeptInfo != null && !CollectionUtils.isEmpty(basePersonInfos)) {
                            BasePersonInfo basePersonInfo = basePersonInfos.get(0);
                            managerInfo.setDDeptname(baseDeptInfo.getDeptName());
                            managerInfo.setDPhone(basePersonInfo.getPhone());
                            managerInfo.setPhoneShort(basePersonInfo.getPhoneShort());
                            managerInfo.setDUsername(basePersonInfo.getUsername());
                            managerInfo.setDType("2");
                            managerInfo.setSType("1");
                            managerInfo.setDUserno(basePersonInfo.getUserno());
                            managerInfo.setDUserjob("关领导");
                            managerInfo.setDutypost(getDupostByH4a(basePersonInfo.getRealRackCode()));
                            managerInfo.setRankCode(basePersonInfo.getRankCode());
                            managerInfo.setFacePath(basePersonInfo.getFacePath());
                        }
                        result.setManagerInfo(managerInfo);
                    }
                    if (CLeader != null) {
                        DutyScheduleInfoTimeDetailDTO CJInfo = new DutyScheduleInfoTimeDetailDTO();
                        BaseDeptInfo baseDeptInfo = baseDeptInfoRepository.getById(CLeader.getDeptId());
                        List<BasePersonInfo> basePersonInfos = basePersonInfoRepository.list(new LambdaQueryWrapper<BasePersonInfo>()
                                .eq(BasePersonInfo::getUserno, CLeader.getLeaderCode()));
                        if (baseDeptInfo != null && !CollectionUtils.isEmpty(basePersonInfos)) {
                            BasePersonInfo basePersonInfo = basePersonInfos.get(0);
                            CJInfo.setDDeptname(baseDeptInfo.getDeptName());
                            CJInfo.setDPhone(basePersonInfo.getPhone());
                            CJInfo.setPhoneShort(basePersonInfo.getPhoneShort());
                            CJInfo.setDUsername(basePersonInfo.getUsername());
                            CJInfo.setDType("2");
                            CJInfo.setSType("2");
                            CJInfo.setDUserno(basePersonInfo.getUserno());
                            CJInfo.setDUserjob("处领导");
                            CJInfo.setDutypost(getDupostByH4a(basePersonInfo.getRealRackCode()));
                            CJInfo.setRankCode(basePersonInfo.getRankCode());
                            CJInfo.setFacePath(basePersonInfo.getFacePath());
                        }
                        result.setCJInfo(CJInfo);
                    }
                    return result;
                case "2":
                case "3":
                    List<DutyScheduleInfo> temp = dutyScheduleInfos.stream()
                            .filter(i -> i.getDStartDateTime().compareTo(now)<0
                                    &&i.getDEndDateTime().compareTo(now)>0).collect(Collectors.toList());
                    if (!CollectionUtils.isEmpty(temp)) {
                        result.setKJInfo(temp.stream().map(i -> {
                            DutyScheduleInfoTimeDetailDTO tempDTO = new DutyScheduleInfoTimeDetailDTO();
                            BeanUtils.copyProperties(i, tempDTO);
                            tempDTO.setFacePath(getPathPath(i));
                            return tempDTO;
                        }).filter(i -> "科领导".equals(i.getDUserjob())).max((a, b) -> a.getCreateTime().compareTo(b.getCreateTime())).orElse(null));
                        result.setCJInfo(temp.stream().map(i -> {
                            DutyScheduleInfoTimeDetailDTO tempDTO = new DutyScheduleInfoTimeDetailDTO();
                            BeanUtils.copyProperties(i, tempDTO);
                            tempDTO.setFacePath(getPathPath(i));
                            return tempDTO;
                        }).filter(i -> "处领导".equals(i.getDUserjob())).max((a, b) -> a.getCreateTime().compareTo(b.getCreateTime())).orElse(null));
                        result.setKJInfo(temp.stream().map(i -> {
                            DutyScheduleInfoTimeDetailDTO tempDTO = new DutyScheduleInfoTimeDetailDTO();
                            BeanUtils.copyProperties(i, tempDTO);
                            tempDTO.setFacePath(getPathPath(i));
                            return tempDTO;
                        }).filter(i -> "关领导".equals(i.getDUserjob())).max((a, b) -> a.getCreateTime().compareTo(b.getCreateTime())).orElse(null));
                    }else {
                        temp = dutyScheduleInfos;
                        result.setKJInfo(temp.stream().map(i->{
                            DutyScheduleInfoTimeDetailDTO tempDTO= new DutyScheduleInfoTimeDetailDTO();
                            BeanUtils.copyProperties(i,tempDTO);
                            tempDTO.setFacePath(getPathPath(i));
                            return tempDTO;
                        }).filter(i->"科领导".equals(i.getDUserjob())).max((a,b)->a.getCreateTime().compareTo(b.getCreateTime())).orElse(null));
                        result.setCJInfo(temp.stream().map(i->{
                            DutyScheduleInfoTimeDetailDTO tempDTO= new DutyScheduleInfoTimeDetailDTO();
                            BeanUtils.copyProperties(i,tempDTO);
                            tempDTO.setFacePath(getPathPath(i));
                            return tempDTO;
                        }).filter(i->"处领导".equals(i.getDUserjob())).max((a,b)->a.getCreateTime().compareTo(b.getCreateTime())).orElse(null));
                        result.setManagerInfo(temp.stream().map(i->{
                            DutyScheduleInfoTimeDetailDTO tempDTO= new DutyScheduleInfoTimeDetailDTO();
                            BeanUtils.copyProperties(i,tempDTO);
                            tempDTO.setFacePath(getPathPath(i));
                            return tempDTO;

                        }).filter(i->"关领导".equals(i.getDUserjob())).max((a,b)->a.getCreateTime().compareTo(b.getCreateTime())).orElse(null));
                    }
                    return result;
                default:
                    return null;
            }
        }
    }

    private DutyScheduleInfo getSignInTaragetScheduleInfo(List<DutyScheduleInfo> dutyScheduleInfos, LocalDateTime now) {
        for (DutyScheduleInfo dutyScheduleInfo : dutyScheduleInfos) {
            ParamDuty paramDuty = paramDutyRepository.getById(dutyScheduleInfo.getDutyTimesId());
            if (paramDuty != null) {
                LocalTime startTime = paramDuty.getDStartTime();
                LocalTime endTime = paramDuty.getDEndTime();
                LocalDateTime startDateTime;
                LocalDateTime endDateTime;
                startDateTime = dutyScheduleInfo.getDDay().atTime(startTime);
                if (now.compareTo(startDateTime) > 0) {
                    return dutyScheduleInfo;
                }
            }
        }
        return dutyScheduleInfos.get(0);
    }

    private String getPathPath(DutyScheduleInfo current) {
        if (current == null) {
            return "";
        }
        BasePersonInfo basePersonInfo = basePersonInfoRepository.getOne(new LambdaQueryWrapper<BasePersonInfo>()
                .eq(BasePersonInfo::getUserno, current.getDUserno()), false);
        if (basePersonInfo == null) {
            return "";
        }
        return basePersonInfo.getFacePath();

    }

    private String getDupostByH4a(String rankCode) {
        String result = "";
        if (rankCode == null) {
            return result;
        }
        switch (rankCode) {
            case "05":
                result = "厅局级正职";
                break;
            case "06":
                result = "厅局级副职";
                break;
            case "07":
                result = "处级人员";
                break;
            case "08":
                result = "处级人员";
                break;
            case "09":
                result = "科长级人员";
                break;
            case "10":
                result = "科长级人员";
                break;
            case "11":
                result = "科员";
                break;
            case "99":
                result = "无行政级别";
                break;
            default:
                return "其他";
        }
        return result;
    }

}
